﻿using System;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using CloudTaobao;

namespace CloudTaobao.Util
{
    public class AutoLogin
    {
        public AutoLoginInfo auto = new AutoLoginInfo();
        private string tokenStatic = "";

        public event AutoLoginFinishedEventHandler autoLoginFinishedEvent;
        public event StartLoadingEventHandler startLoadingEvent;
        public event EndLoadingEventHandler endLoadingEvent;

        public void autoLogin(string token)
        {
            try
            {
                tokenStatic = token;
                LoginClient client = new LoginClient();
                client.addParameter("api", "com.taobao.client.sys.autologin");
                client.addParameter("data", "{\"token\":\"" + token + "\"}");
                client.addParameter("t", DateTime.Now.Millisecond.ToString());
                client.sendRequest(new AsyncCallback(HandleAutoLoginResponse));
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    startLoadingEvent(this, new StartLoadingEventArgs("正在自动登录"));
                });
            }
            catch (Exception ex)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    endLoadingEvent();
                    MessageBox.Show(ex.Message);
                });
            }
        }

        private void HandleAutoLoginResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                byte[] tmp = new byte[streamResult.Length];
                streamResult.Read(tmp, 0, tmp.Length);
                string result = "";
                for (int i = 0; i != tmp.Length; i++)
                {
                    char tmpChar = (char)tmp[i];
                    result += tmpChar;
                }
                MemoryStream jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(result));
                DataContractJsonSerializer jsonPaser = new DataContractJsonSerializer(typeof(AutoLoginInfo));
                auto = jsonPaser.ReadObject(jsonStream) as AutoLoginInfo;

                if (auto.ret.ElementAt(0).Contains("INVALID_TOKEN"))
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        endLoadingEvent();
                        MessageBox.Show("会话已经过期，请返回到主界面重新登录");
                    });
                    return;
                }


                AppSettings settings = new AppSettings();
                settings.nick = auto.data.nick;
                settings.token = tokenStatic;
                settings.top_session = auto.data.topsession;
                settings.valid = true;

                App app = Application.Current as App;
                app.sessionInfo = new Dictionary<string, string>();
                app.sessionInfo.Add("nick", auto.data.nick);
                app.sessionInfo.Add("top_session", auto.data.topsession);
                app.sessionInfo.Add("token", tokenStatic);

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    endLoadingEvent();
                    autoLoginFinishedEvent();
                });
            }
            catch (Exception)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    endLoadingEvent();
                    MessageBox.Show("自动登录失败");
                });
                return;
            }
        }
    }

    public class AutoLoginInfo
    {
        public string api;
        public string v;
        public List<string> ret;
        public autoLoginDateInfo data;
        public AutoLoginInfo()
        {
            api = "";
            v = "";
            ret = new List<string>();
            data = new autoLoginDateInfo();
        }
    }

    public class autoLoginDateInfo
    {
        public string topsession;
        public string sid;
        public string logintime;
        public string ecode;
        public string nick;
        public autoLoginDateInfo()
        {
            topsession = "";
            sid = "";
            logintime = "";
            ecode = "";
            nick = "";
        }
    }
}
